var config = require("../config/config.js");
var storageManage = require("../manage/storageManage.js");

var API = {
  ACCESS_SERVER: true,
  api: function (action, payload, succ_cb, error_cb) {
    var that = this;
    wx.request({
      url: config.serverUrl,
      data: {
        'action': action,
        'payload': Object.assign({}, payload)
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'token': storageManage.getServiceUser().token,
      },
      success: function (res) {
        if (res.data.e == 0) {
          succ_cb(res.data);
        } else {
          console.error(res.data)
          if (res.data.e < 0) { //服务器登录失效
            that.login(function () {
              that.api(action, payload, succ_cb, error_cb)
            })
          } else {
            succ_cb(res.data);
          }
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '请求超时，请稍后再试',
          icon: 'none'
        })
        console.error(res)
        setTimeout(function () {
          error_cb(res);
        }, 1000)
      }
    });

  },
  //创建模板
  send_template: function (e) {
    this.api('send_template', { form_id: e.detail.formId }, function (data) {
    }, function () { });
  },
  check: function (callback) {
    var that = this;
    wx.checkSession({
      success: function () {
        //session 未过期，并且在本生命周期一直有效
        console.log("未过期")
        that.setting(function () {  //是否授权
          callback();
        })
      },
      fail: function () {
        that.login(callback) //重新登录
      }
    });

  },

  login: function (callback_) {
    var that = this;
    console.log("过期")
    wx.login({ //微信登录
      success: function (res) {
        storageManage.setWxCode(res.code);
        that.api('login', {
          "code": res.code
        }, function (data) {
          storageManage.setServiceUser(data.data);
          that.setting(function () { callback_(); })
        }, function (e, ed) {
          console.error('fail=' + e + " " + ed);
        })
      },
      fail: function () {

      },
      complete: function () {

      }

    })

  },
  setting: function (fun) {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          fun()
        } else {
          wx.reLaunch({
            url: '../getInfoError/getInfoError',
          })
        }
      }
    })
  }
};




export default API;